package com.kcht.sylyg08.service;

import com.kcht.adp.common.event.ADPEventPublisher;
import com.kcht.adp.common.event.EventLevel;
import com.kcht.sylyg08.dao.IContainerDao;
import com.kcht.sylyg08.service.model.ContainerActionDetails;
import com.kcth.sylyg08.entity.Container;
import com.kcth.sylyg08.entity.ContainerStatus;

import javax.ejb.EJB;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import java.util.Objects;

@ApplicationScoped
public class ContainerActionHandler {

    @EJB
    private IContainerDao cDao;

    @Inject
    private IContainerStatusService containerStatusService;

    /**
     * 处理错误的料框动作，并将料框标记为异常
     *
     * @param action 料框动作
     */
    public void errorContainerAction(@Observes ContainerActionDetails action) {
        if (action.getRtnCode() < -1 && action.getRtnCode() != -99) {
            if (Objects.nonNull(action.getContainerId())) {
                Container container = cDao.get(action.getContainerId());
                container.setIsError(true);
                container.setErrorDetals(action.getLocation());
                cDao.merge(container);
            }
        }
    }

    /**
     * 处理异常料框
     *
     * @param containerId 料框编号
     * @param status      料框目标状态
     * @param username    处理用户
     * @param details     详情
     */
    public void errorContainerHandle(String containerId, ContainerStatus status, String username, String details) {
        containerStatusService.changeContainerStatusByIntervene(containerId, status, username, details);
        Container container = cDao.get(containerId);
        container.setIsError(false);
        cDao.merge(container);
        ContainerActionDetails containerActionDetails = new ContainerActionDetails();
        containerActionDetails.setContainerId(containerId);
        containerActionDetails.setRtnCode(-99);
        ADPEventPublisher.publishEvent(containerActionDetails, EventLevel.Negligible);
    }
}
